package com.example.eurekac.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.eurekac.entity.Audience;
import com.example.eurekac.service.UserService;
import com.example.eurekac.utils.RedisUtil;
import com.example.eurekac.utils.WeChatUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @program: config-client
 * @description: 微信接口
 * @author: ZhouGuoFeng
 * @create: 2018-12-12 16:40
 **/
@RefreshScope
@RestController
@RequestMapping(value = "/weChat")
public class WeChatController {
    private static Logger logger= LoggerFactory.getLogger(TestController.class);
    @Autowired
    private Audience audience;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    UserService userService;

    /**
     *获取唯一标识
     * @param code
     * @return
     */
    @RequestMapping(value = "/getSessionKey",method = RequestMethod.POST)
    public String getSessionKey(@RequestBody String code){
        JSONObject jsonp = JSON.parseObject(code);
        String scode=jsonp.getString("code");
        String appid="wx0adddff974ffb7e7";
        String AppSecret="d089ac5dfe41f439925e214fa24f2370";
        Map<String,String> data=null;
        String ret=null;
        try {
             data=WeChatUtil.getURLContent(appid,scode,AppSecret);
             //sha1加密
            ret= DigestUtils.sha1Hex(data.get("openID"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }
    /**
     *验证用户信息
     * @param data
     * @return
     */
    @RequestMapping(value = "/validateUser",method = RequestMethod.POST)
    public String validateUser(@RequestBody String data){

        String ret=null;
        JSONObject jsonp = JSON.parseObject(data);
        String rawData=jsonp.getString("rawData");
        String signature =jsonp.getString("signature");
        String dd= DigestUtils.sha1Hex(rawData+WeChatUtil.session_key);
        if(signature.equals(dd)){
            ret="相等";
        }else{
            ret="不相等";
        }
        return ret;
    }
}
